import { Button, Card, Col, Divider, Form,Icon,Input, Row, Select,InputNumber, message } from "antd";
import React from "react";
import styles from "@/pages/TenantManagement/index.less"
import { modelListTenant } from "@/services/languageModel";
import { getUuid } from "@/utils/utils";
import { preChargingAdd, preChargingDetail, preChargingEdit } from "@/services/chargingManage";
import { formatMessage } from 'umi-plugin-react/locale';

class PreChargingEdit extends React.Component{
  constructor(props){
    super(props);
    this.state = { 
      modelList:[],
      originalModelList:[],
      customBillingList:[{frontId:getUuid()}],
      id:''
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }

    this.getLlmList()
    if(this.props.location.query.id){
      this.getDetail(this.props.location.query.id)
    }
    
  }

  getDetail = id => {
    this.setState({id},async () => {
      const res = await preChargingDetail({id})
      this.props.form.setFieldsValue(res)
    })
  }

  getLlmList = async () => {
    const res = await modelListTenant()
    let arr = []
    let item = []
    for(const i in res){
      item.push(res[i])
      if(i % 2 == 1 || i == res.length - 1){
        arr.push(item)
        item = []
      }
    }
    
    this.setState({modelList:arr,originalModelList:res})
  }


  addCustomBill = () => {
    const list = this.state.customBillingList;
    list.push({frontId:getUuid()})
    this.setState({customBillingList:list})
  }

  delCustomBill = frontId => {
    let list = this.state.customBillingList;
    let newList = list.filter(item => item.frontId != frontId);
    this.setState({customBillingList:newList})
  }

  doValidate = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        const { modelList,customBillingList,originalModelList } = this.state
        console.log(values);
        let obj = {}
        for(const item of Object.keys(values)){
          if(item.indexOf("_") === -1){
            obj[item] = values[item]
          }
        }

        //处理模型
        let newModelList = originalModelList.map(item => {
          return {
            modelId:item.id,
            tokenUnit:values[item.id+'_Unit'],
            tokenPrice:values[item.id+'_Price'],
            tokenModulus:values[item.id+'_Modulus'],
          }
        })

        //处理自定义
        let newCustomBillingList = customBillingList.map(item => {
          return {
            id:item.id,
            name:values[item.frontId+'_name'],
            unit:values[item.frontId+'_unit'],
            price:values[item.frontId+'_price'],
            modulus:values[item.frontId+'_modulus'],
          }
        })

        this.doSave({...obj,modelList:newModelList,customBillingList:newCustomBillingList})
        
      }
    })
  }

  doSave = async (data) => {
    let res = {}
    if(this.state.id){
      data.id = this.state.id
      res = await preChargingEdit(data)
    }else{
      res = await preChargingAdd(data)
    }
     
    message.info(res.message)
    this.goBack()
  }

  goBack = () => {
    this.props.history.push({ pathname: '/ChargingManage/preCharging' })
  }

  renderNumberBox = (getFieldDecorator,unit,price,modulus) => (
    <div style={{display:'flex',alignItems:"center",gap:'3px'}}>      
      <div className={styles.numberBox}>
        <div className={styles.prevBox} style={{width:40}}>每</div>
        <Form.Item style={{marginBottom:0,marginRight:0}}>
          {
            getFieldDecorator(unit,{initialValue:1})(
              <Select style={{width:52}}>
                <Select.Option value={1}>月</Select.Option>
                <Select.Option value={2}>年</Select.Option>
                <Select.Option value={0}>M</Select.Option>
              </Select>
            )
          }
        </Form.Item>
        <Form.Item style={{marginBottom:0,marginRight:0}}>
          {
            getFieldDecorator(price,{initialValue:0})(
              <InputNumber precision={0} min={0} />
            )
          }
        </Form.Item>
        <div className={styles.suffixBox} style={{width:40,textAlign:"center"}}>元</div>
        <Form.Item style={{marginBottom:0,marginRight:0}}>
          {
            getFieldDecorator(modulus,{initialValue:1})(
              <InputNumber precision={0} min={0} />
            )
          }
        </Form.Item>
        <div className={styles.suffixBox} style={{width:40,textAlign:"center"}}>系数</div>
      </div>
    </div>
  )

  render(){
    const { form:{getFieldDecorator},id,current } = this.props
    const { modelList,customBillingList } = this.state;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
    };
    return(
      <Card bordered={false}>
        <Form {...formItemLayout}>
          <h3>基础信息</h3>
          <Form.Item label={'计费名称'}>
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '计费名称必填' }],
              getValueFromEvent: event => event.target.value.replace(/\s+/g, '')
            })(<Input placeholder={'请填写计费名称'} style={{ width: '400px' }} autoComplete="off" />)}
          </Form.Item>
          <Form.Item label={'备注'}>
            {getFieldDecorator('remark', {
              getValueFromEvent: event => event.target.value.replace(/\s+/g, '')
            })(<Input.TextArea placeholder={''} style={{ width: '400px' }} autoComplete="off" autoSize={{minRows:3,maxRows:10}} />)}
          </Form.Item>

          <Divider style={{marginTop:0}} />

          <h3>资源计费规则</h3>
          <Row>
            <Col span={12}>
              <Form.Item label='磁盘总量'>
                {this.renderNumberBox(getFieldDecorator,'diskUnit','diskPrice','diskModulus')}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label='使用时长'>
                {this.renderNumberBox(getFieldDecorator,'useTimeUnit','useTimePrice','useTimeModulus')}
              </Form.Item>
            </Col>
          </Row>

          <Divider style={{marginTop:0}} />

          <h3>知识量计费规则</h3>
          <Row>
            <Col span={12}>
              <Form.Item label='知识点'>
                {this.renderNumberBox(getFieldDecorator,'qaUnit','qaPrice','qaModulus')}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label='文档'>
                {this.renderNumberBox(getFieldDecorator,'docUnit','docPrice','docModulus')}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label='导图'>
                {this.renderNumberBox(getFieldDecorator,'atlasUnit','atlasPrice','atlasModulus')}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label='多轮'>
                {this.renderNumberBox(getFieldDecorator,'dialogUnit','dialogPrice','dialogModulus')}
              </Form.Item>
            </Col>
          </Row>

          <Divider style={{marginTop:0}} />

          <h3>模型能力计费规则</h3>
          <Row>
            <Col span={12}>
              <Form.Item label='助手'>
                {this.renderNumberBox(getFieldDecorator,'agentUnit','agentPrice','agentModulus')}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label={formatMessage({ id: 'menu.assistantCenter' })}>
                {this.renderNumberBox(getFieldDecorator,'assistantUnit','assistantPrice','assistantModulus')}
              </Form.Item>
            </Col>
          </Row>
          {
            modelList.map((item,itemIndex) => {
              return (
                <Row key={itemIndex}>
                  {
                    item.map(model => {
                      return (
                        <Col span={12} key={model.id}>
                          <Form.Item label={model.name}>
                            {this.renderNumberBox(getFieldDecorator,model.id+'_Unit',model.id+'_Price',model.id+'_Modulus')}
                          </Form.Item>
                        </Col>
                      )
                    })
                  }
                </Row>
              )
            })
          }

          <Divider style={{marginTop:0}} />

          <h3>企业用户限制规则</h3>
          <Row>
            <Col span={12}>
              <Form.Item label='企业'>
                {this.renderNumberBox(getFieldDecorator,'enterpriseUnit','enterprisePrice','enterpriseModulus')}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label='用户'>
                {this.renderNumberBox(getFieldDecorator,'userUnit','userPrice','userModulus')}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label='企业管理员'>
                {this.renderNumberBox(getFieldDecorator,'enterpriseAdminUnit','enterpriseAdminPrice','enterpriseAdminModulus')}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label='用户管理员'>
                {this.renderNumberBox(getFieldDecorator,'userAdminUnit','userAdminPrice','userAdminModulus')}
              </Form.Item>
            </Col>
          </Row>

          <Divider style={{marginTop:0}} />

          <h3>自定义计费<Button type="primary" size="small" style={{marginLeft:10}} onClick={this.addCustomBill}>添加</Button></h3>
          {
            customBillingList.map(item => {
              return (
                <Row key={item.frontId}>
                  <Col span={24}>
                    <Form.Item>
                      <div style={{display:"flex",alignItems:"center"}}>
                        <div className={styles.numberBox}>
                          <div className={styles.prevBox}>项目</div>
                          <Form.Item style={{marginBottom:0,marginRight:0}}>
                            {getFieldDecorator(item.frontId+'_name')(<Input style={{width:"100%"}} />)}
                          </Form.Item>
                        </div>
                        {this.renderNumberBox(getFieldDecorator,item.frontId+'_unit',item.frontId+'_price',item.frontId+'_modulus')}
                        <Icon type="close-square" style={{cursor:"pointer",marginLeft:10}} onClick={() => this.delCustomBill(item.frontId)} />
                      </div>
                    </Form.Item>
                  </Col>
                </Row>
              )
            })
          }

          <Divider style={{marginTop:0}} />

          <h3>计费说明</h3>

          <div>
            <p>1、计费清单将于次月第一天自动生成，汇总并展示上一个月的计费详情。</p>
            <p>2、计费规则的调整将在下一次计费周期开始时生效。</p>
            <p>3、已生成的计费数据固定，不会因计费规则的调整而发生变化。</p>
            <p>4、计费清单提供历史计费规则的查询功能，便于追溯和了解过去的计费标准。</p>
          </div>

          <Form.Item>
            <Button style={{marginRight:10}} onClick={this.goBack}>取消</Button>
            <Button type="primary" onClick={this.doValidate}>保存</Button>
          </Form.Item>
          
        </Form>
      </Card>
    )
  }
}

export default Form.create()(PreChargingEdit)